"use client";

import { useState, useEffect } from "react";
import { Button, Popover } from "antd";
import { useMessage } from "@/hooks/useMessage";
import { useWechatShare } from "@/hooks/useWechatShare";
import { ArrowUpOnSquareIcon, LinkIcon, CheckIcon } from "@heroicons/react/24/outline";
import dynamic from "next/dynamic";

const QRCodeWrapper = dynamic(() => import("./QRCodeWrapper"), {
  ssr: false,
  loading: () => <p>加载中...</p>,
});

const WeChatShareGuide = dynamic(() => import("./WeChatShareGuide"), {
  ssr: false,
});

interface ShareButtonProps {
  title?: string;
  description?: string;
  imageUrl?: string;
}

export default function ShareButton({ title, description, imageUrl }: ShareButtonProps) {
  const message = useMessage();
  const [currentUrl, setCurrentUrl] = useState("");
  const [copied, setCopied] = useState(false);
  const [showWeChatGuide, setShowWeChatGuide] = useState(false);

  useEffect(() => {
    if (typeof window !== "undefined") {
      setCurrentUrl(window.location.href);
    }
  }, []);

  // 微信分享配置
  const shareData = {
    title: title || (typeof document !== "undefined" ? document.title : "AI产品之家"),
    desc: description || "AI产品之家 - 做好AI产品，用好AI产品",
    link: currentUrl,
    imgUrl: imageUrl || `${process.env.NEXT_PUBLIC_SITE_URL}/logo.png`,
  };

  const { isWechat } = useWechatShare(shareData);
  // const isWechat = true; // test
  const handleCopy = () => {
    navigator.clipboard.writeText(currentUrl).then(() => {
      setCopied(true);
      message.success("链接已复制！");
      setTimeout(() => setCopied(false), 2000);
    });
  };

  const handleShareClick = () => {
    if (isWechat) {
      setShowWeChatGuide(true);
    }
    // For non-wechat browsers, the Popover will handle the click.
  };

  const webShareContent = (
    <div className='flex flex-col items-center space-y-4 p-2'>
      <QRCodeWrapper value={currentUrl} size={128} />
      <Button onClick={handleCopy} icon={copied ? <CheckIcon className='w-4 h-4' /> : <LinkIcon className='w-4 h-4' />} block>
        {copied ? "已复制" : "复制链接"}
      </Button>
    </div>
  );

  if (isWechat) {
    return (
      <>
        <Button icon={<ArrowUpOnSquareIcon className='w-4 h-4' />} onClick={handleShareClick}>
          分享
        </Button>
        {showWeChatGuide && <WeChatShareGuide onClose={() => setShowWeChatGuide(false)} />}
      </>
    );
  }

  return (
    <Popover content={webShareContent} trigger='click'>
      <Button icon={<ArrowUpOnSquareIcon className='w-4 h-4' />}>分享</Button>
    </Popover>
  );
}
